/**
 *
 * 版权所有 © cybersky.com
 *
 */
package cn.cybertron.primus.report.data;

import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.nutz.lang.Mirror;

/**
 * 报表数据类
 * @author ch
 *
 */
public class ReportData implements Serializable {

	private static final long serialVersionUID = -7040473104549195520L;

	/**
	 * 对应字段名
	 */
	private List<String> fieldNames;
	
	/**
	 * 对应字段类型，java类全路径名
	 */
	private List<Class<?>> fieldClazzs;
		
	/**
	 * 数据记录
	 */
	private List<ReportDataRecord> data;
		
	public ReportData() {
		
	}

	public List<String> getFieldNames() {
		return fieldNames;
	}

	public void setFieldNames(List<String> fieldNames) {
		this.fieldNames = fieldNames;
	}

	public List<Class<?>> getFieldClazzs() {
		return fieldClazzs;
	}

	public void setFieldClazzs(List<Class<?>> fieldClazzs) {
		this.fieldClazzs = fieldClazzs;
	}

	public List<ReportDataRecord> getData() {
		return data;
	}

	public void setData(List<ReportDataRecord> data) {
		this.data = data;
	}
	
	/**
	 * 排序
	 */
	public void sort(int index) {
		Class<?> clazz = fieldClazzs.get(index);
		// 排序
		Collections.sort(data, new DataComparator(index, clazz));
	}
	
	private static class DataComparator implements Comparator<ReportDataRecord> {

		private int index;

		private Class<?> clazz;

		private Mirror<?> me;

		public DataComparator(int index, Class<?> clazz) {
			this.index = index;
			this.clazz = clazz;
			this.me = Mirror.me(clazz);
		}

		@Override
		public int compare(ReportDataRecord o1, ReportDataRecord o2) {
			double result;
			if(clazz == String.class) {
				String s1 = (String) me.born(o1.getItem(index));
				String s2 = (String) me.born(o2.getItem(index));
				result = s1.compareTo(s2);
			} else if(clazz == Date.class) {
				Date d1 = (Date) o1.getItem(index);
				Date d2 = (Date) o2.getItem(index);
				result = d1.getTime() - d2.getTime();
			}  else {
				Double d1 = (Double) me.born(o1.getItem(index));
				Double d2 = (Double) me.born(o2.getItem(index));
				result = d1 - d2;
			}

			return result>0? 1: -1;
		}
		
	}
}
